package com.eco.fanliapp.admin.controller.web;

import com.eco.fanliapp.admin.annotation.SysLogAnnotation;
import com.eco.fanliapp.admin.common.BaseController;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.service.impl.AppUserServiceImpl;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.MapValueHelper;
import com.eco.fanliapp.vo.UserVO;
import com.github.pagehelper.PageInfo;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;


@RestController

@RequestMapping("/web/withdrawal")
public class WithdrawalController extends BaseController {

    @Autowired
    private IAppWithdrawalService withdrawalService;

    @Autowired
    private AppUserServiceImpl userService;

    @Autowired
    private IAppNewsLogService iAppNewsLogService;

    @Autowired
    private IAdministratorService administratorService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private SysLogCommon sysLogCommon;
    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;


    @RequestMapping("/selectWithdrawalList")
    public ServerResponse<PageInfo> selectWithdrawalList(@RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "10") int pageSize,
                                                          String startTime,String endTime, Integer withdrawalType, Integer applicantStatus,
                                                         String keyWord,Integer transferState,String dealStartTime,String dealEndTime) {
        Integer companyId =  getAuthentication().getCompanyId();
        if(companyId == 1){
            companyId = null;
        }
        return withdrawalService.selectAppWithdrawalList(currentPage, pageSize, companyId, withdrawalType, null, applicantStatus, startTime, endTime, keyWord,transferState,dealStartTime,dealEndTime);
    }



    @SysLogAnnotation(value = "添加提现", userType = 2)
    @PostMapping("/addWithdrawal")
    @Synchronized
    public ServerResponse
    addWithdrawal(@RequestBody AppWithdrawal withdrawal) {

        return withdrawalService.insertSelective(withdrawal);
    }


    @SysLogAnnotation(value = "添加提现", userType = 2)
    @PostMapping("/insertOrUpdateOrInsertWithdrawal")
    @Synchronized
    public ServerResponse<List>
    insertOrUpdateOrInsertWithdrawal(@RequestBody AppWithdrawal withdrawal) {

        return withdrawalService.insertOrUpdateSelective(withdrawal);

    }


    @RequestMapping("/selectWithdrawalListByKeyWord")
    public ServerResponse<PageInfo> selectWithdrawalListByKeyWord(Integer applicantStatus, String startTime, String endTime, String keyWord,
                                                                  @RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "10") int pageSize) {
        Integer companyId = getAuthentication().getCompanyId();
        return withdrawalService.selectAppWithdrawalListByKeyWord(applicantStatus, startTime, endTime, keyWord, currentPage, pageSize, companyId);
    }


    @RequestMapping("/downloadWithdrawalDetailsByKeyWord")
    public void downloadWithdrawalDetailsByKeyWord(HttpServletResponse response, Integer applicantStatus, String startTime,
                                                   String endTime, String keyWord) {
        Integer companyId = getAuthentication().getCompanyId();
        withdrawalService.downloadAppWithdrawalDetailsByKeyWord(response, applicantStatus, startTime, endTime, keyWord, companyId);
    }


    /**
     * 提现记录导出 (新)
     *
     * @param response
     */
    @RequestMapping("/export")
    @SysLogAnnotation(value = "下载了提现记录",userType = 2)
    public void exportExcel(HttpServletResponse response, Integer applicantStatus, String startTime,
                            String endTime, String keyWord, Integer withdrawalType,Integer transferState,String dealStartTime,String dealEndTime) {
        Integer companyId = getAuthentication().getCompanyId();
        withdrawalService.export(response, applicantStatus, startTime, endTime, keyWord, companyId, withdrawalType,transferState,dealStartTime,dealEndTime);
    }

    /**
     * 提现记录导入(新) 批量修改提现状态
     *
     * @param response
     */
    @RequestMapping("/import")
    @SysLogAnnotation(value = "提现记录导入",userType = 2)
    public ServerResponse importExcel(HttpServletResponse response, MultipartFile file) {

        return ServerResponse.createBySuccess("导入成功", withdrawalService.importExcel(response, file));
    }


    @SysLogAnnotation(value = "提现确认", userType = 2)
    @RequestMapping(method = RequestMethod.POST, value = "/updateSum")
    public ServerResponse updateSum(@RequestBody HashMap<String, Object> hashMap) {
        UserVO authentication = getAuthentication();
        Administrator administrator = administratorService.getById(authentication.getUserId());
        SysLog sysLog = new SysLog();
        sysLog.setUserId(authentication.getUserId());
        MapValueHelper mapValueHelper = new MapValueHelper(hashMap);
        int id = mapValueHelper.getInt("id");
        AppWithdrawal appWithdrawal1 = withdrawalService.selectAppWithdrawalById(Long.valueOf(id));
        //AppUser appUser = userService.selectAppUserByUserId(appWithdrawal1.getUserId());
        sysLog.setMethodExplain(administrator.getAdminitratorName() + "确认了用户" + appWithdrawal1.getUserRealName() + "申请的提现记录 提现金额为：" + mapValueHelper.getDouble("amount"));
        if (appWithdrawal1.getApplicantStatus() != 1) {
            sysLog.setResponseParams("提现失败：不是未处理状态！");
            sysLogCommon.save(sysLog);
            return ServerResponse.createByErrorMessage("提现失败：不是未处理状态！");
        }
        hashMap.put("applicantStatus", 2);
        hashMap.put("processingResults", "成功");
        hashMap.put("processingTime", System.currentTimeMillis());

        Double amount = mapValueHelper.getDouble("amount");
        int i = withdrawalService.updateSum(hashMap);
        if (i > 0) {
            AppWithdrawal appWithdrawal = withdrawalService.selectAppWithdrawalById(Long.valueOf(id));


            iAppNewsLogService.newsType(appWithdrawal.getUserId(),
                    NewsEnumLog.NEWS_CASH_SUCC.getNewsType(),
                    BigDecimalUtils.Format(amount), amount.toString());
            sysLog.setResponseParams("成功");
            sysLogCommon.save(sysLog);
            return ServerResponse.createBySuccessMessage("提现处理成功");
        }
        sysLog.setResponseParams("失败");
        sysLogCommon.save(sysLog);
        return ServerResponse.createByErrorMessage("提现处理失败！");
    }

    @SysLogAnnotation(value = "提现拒绝", userType = 2)
    @RequestMapping(method = RequestMethod.POST, value = "/updateRefuseSum")
    public ServerResponse updateRefuseSum(@RequestBody HashMap<String, Object> hashMap) {
        UserVO authentication = getAuthentication();
        Administrator administrator = administratorService.getById(authentication.getUserId());
        SysLog sysLog = new SysLog();
        sysLog.setUserId(authentication.getUserId());
        MapValueHelper mapValueHelper = new MapValueHelper(hashMap);
        int id = mapValueHelper.getInt("id");
        AppWithdrawal appWithdrawal1 = withdrawalService.selectAppWithdrawalById(Long.valueOf(id));
        //AppUser appUser = userService.selectAppUserByUserId(appWithdrawal1.getUserId());
        sysLog.setMethodExplain(administrator.getAdminitratorName() + "拒绝了用户" + appWithdrawal1.getUserRealName() + "申请的提现记录 提现金额为：" + mapValueHelper.getDouble("amount"));
        if (appWithdrawal1.getApplicantStatus() != 1) {
            sysLog.setResponseParams("提现失败：不是未处理状态！");
            sysLogCommon.save(sysLog);
            return ServerResponse.createByErrorMessage("提现失败：不是未处理状态！");
        }
        hashMap.put("applicantStatus", 3);
        hashMap.put("processingResults", "失败");
        hashMap.put("processingTime", System.currentTimeMillis());
        Double amount = mapValueHelper.getDouble("amount");
        int i = withdrawalService.updateSum(hashMap);

        if (i > 0) {
            AppWithdrawal appWithdrawal = withdrawalService.selectAppWithdrawalById(Long.valueOf(id));
            int i1 = userService.updateAppUseraddbalance(appWithdrawal.getUserId(), BigDecimal.valueOf(amount));

            if (i1 > 0) {
                //获取用户账户
                SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(appWithdrawal.getUserId());
                //变动前可用余额
                BigDecimal beforeBalance = syUserMoney.getCashBalanceAmount();
                //新增用户余额变动日志记录
                syUserMoneyLogService.addSyUserMoneyLog(appWithdrawal.getUserId(), beforeBalance, BigDecimal.valueOf(amount), "支付宝提现失败", 2, 0);

                iAppNewsLogService.newsType(appWithdrawal.getUserId(),
                        NewsEnumLog.NEWS_CASH_FAIL.getNewsType(),
                        BigDecimalUtils.Format(amount));
                sysLog.setResponseParams("成功");
                sysLogCommon.save(sysLog);
                return ServerResponse.createBySuccessMessage("拒绝提现ok");

            }
            sysLog.setResponseParams("失败");
            sysLogCommon.save(sysLog);
            return ServerResponse.createByErrorMessage("拒绝提现失败");
        }
        sysLog.setResponseParams("失败");
        sysLogCommon.save(sysLog);
        return ServerResponse.createByErrorMessage("拒绝提现失败");
    }

    @SysLogAnnotation(value = "删除提现", userType = 2)
    @RequestMapping(method = RequestMethod.GET, value = "/delete")
    public ServerResponse delete(Long id) {
        int i = withdrawalService.deleteAppWithdrawalById(id);
        if (i > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }


    @RequestMapping(method = RequestMethod.GET, value = "/findAll")
    public ServerResponse findAll() {
        return withdrawalService.findAll();
    }


}
